﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Hank.BrowserParse;

namespace WareDealer.Works
{
    /// <summary>
    /// 商品搜索工作项
    /// </summary>
    [DisplayName("商品搜索工作项")]
    public class JdSearchWork : JdWorkItem
    {
        public override void ExecItem()
        {
            ResultItems = GetSearchList(WorkItems.ToString());
        }

        private string GetURLResult(string website)
        {
            try
            {
                if (string.IsNullOrEmpty(website))
                {
                    return null;
                }
                HttpItem item = new HttpItem();
                SFHttpHelper helper = new SFHttpHelper();
                HttpResult result = new HttpResult();
                item.URL = website;
                item.Encoding = Encoding.UTF8;
                item.Header.Add("Accept-Encoding", "gzip, deflate");
                item.ContentType = "text/html";
                item.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)";
                item.Cookie = "unick=%E8%B5%96%E7%9A%AE%E9%B9%8F; _pst=; __jdv=122270672|shop.beva.com|t_328130888_|tuiguang|138ba3ffa5e749eda05260183d68b1e5; unpl=V2_ZzNtbUAEQRZyChJVKExVB2IEEwlLXxQVfQ8UXH4QCwVvABtZclRCFXIUR11nGFsUZwMZXENcQhNFC3ZWfhhcA2UCEFtyZ0sdGwh2V3spXARnMxteRlBHFXULRGRLGVo1ZwoaXUdWQSUxZkFVKx0JAm5XRl4VU0YlaQh2VUsYbEhuABZaRldDFnc4R2R4; jdAddrId=; jdAddrName=; areaId=22; rkv=V09; __jda=122270672.825651123.1469948136.1470536471.1470549502.4; __jdb=122270672.3.825651123|4.1470549502; __jdc=122270672; ipLoc-djd=22-1930-50949-52154; ipLocation=%u56DB%u5DDD; mx=0_X; xtest=45532.29042.14ee22eaba297944c96afdbe5b16c65b.14ee22eaba297944c96afdbe5b16c65b; __jdu=825651123";
                result = helper.GetHtml(item);
                return result.Html;
            }
            catch (Exception ex)
            {
                ImportThreads.LastMsg = "失败：未获取到网页数据";
                Debug.WriteLine(ex.Message);
                return null;
            }
            //string rtn = HttpHelper.GetResponseUTF(url, "get", string.Empty);
            //return rtn;
        }

        readonly List<WebSiteModel> _sites = new List<WebSiteModel>();

        private void ParseResult(string rtn)
        {

            MatchCollection wNameList = Regex.Matches(rtn, "<a target=\"_blank\" title=\"(.*)\"\\s*href=\"//item.jd.com/\\d{1,14}.html\"\\s*onclick=\"(.*)\">\\s*<em>");
            for (int i = 0; i < wNameList.Count; i++)
            {
                string tt = wNameList[i].Value;
                string wUrl = Regex.Match(tt, "//item.jd.com/\\d{1,14}.html").Value;
                string wName = Regex.Match(tt, "title=\"(.*)\" ").Value.Replace("title=", "");
                if (!_sites.Exists(t => t.url == wUrl))
                {
                    _sites.Add(new WebSiteModel()
                    {
                        title = wName,
                        url = wUrl
                    });
                }
            }
        }

        /// <summary>
        /// 获取商品检索结果
        /// </summary>
        /// <param name="keyword">关键词</param>
        /// <returns>网站数据列表</returns>
        public List<WebSiteModel> GetSearchList(string keyword)
        {
            if (string.IsNullOrEmpty(keyword))
            {
                return null;
            }
            #region 说明
            //搜索结果（第一页）
            //http://search.jd.com/Search?keyword=%E5%B0%8F%E9%BA%A6%E7%8E%8B%E5%95%A4%E9%85%92&enc=utf-8&suggest=1.his.0&wq=&pvid=q1r6s1ni.7uj14o
            //http://search.jd.com/Search?keyword=%E8%92%99%E7%89%9B&enc=utf-8&wq=%E8%92%99%E7%89%9B&pvid=do2gzjri.fhkknd
            //http://search.jd.com/Search?keyword=%E7%89%B9%E4%BB%91%E8%8B%8F&enc=utf-8&pvid=4seb1kri.fhkknd
            //第二页
            //http://search.jd.com/Search?keyword=%E5%8D%8E%E4%B8%BA&enc=utf-8&qrst=1&rt=1&stop=1&vt=2&bs=1&ev=exbrand_%E5%8D%8E%E4%B8%BA%EF%BC%88HUAWEI%EF%BC%89%40&page=11&s=301&click=0
            //http://search.jd.com/Search?keyword=%E8%92%99%E7%89%9B&enc=utf-8&wq=%E8%92%99%E7%89%9B&pvid=o7m60kri.fhkknd#keyword=%E8%92%99%E7%89%9B&enc=utf-8&qrst=1&rt=1&stop=1&vt=2&offset=1&page=3&s=60&click=0
            //第三页
            //http://search.jd.com/Search?keyword=%E8%92%99%E7%89%9B&enc=utf-8&wq=%E8%92%99%E7%89%9B&pvid=do2gzjri.fhkknd#keyword=%E8%92%99%E7%89%9B&enc=utf-8&qrst=1&rt=1&stop=1&vt=2&offset=1&page=5&s=120&click=0
            //第四页
            //http://search.jd.com/Search?keyword=%E8%92%99%E7%89%9B&enc=utf-8&wq=%E8%92%99%E7%89%9B&pvid=o7m60kri.fhkknd#keyword=%E8%92%99%E7%89%9B&enc=utf-8&qrst=1&rt=1&stop=1&vt=2&offset=1&page=7&s=180&click=0
            //京东配送
            //http://search.jd.com/Search?keyword=%E7%89%B9%E4%BB%91%E8%8B%8F&enc=utf-8&wq=teluns&pvid=qh570kri.fhkknd#keyword=%E7%89%B9%E4%BB%91%E8%8B%8F&enc=utf-8&qrst=1&rt=1&stop=1&vt=2&offset=1&wtype=1&click=1
            /*<div id="J_topPage" class="f-pager">
						<span class="fp-text">
							<b>1</b><em>/</em><i>178</i>
						</span>
						<a class="fp-prev disabled" href="javascript:;">&lt;</a>
						<a class="fp-next" href="javascript:;">&gt;</a>
					</div>
					<div class="f-result-sum">共<span id="J_resCount" class="num">5311</span>件商品</div>
             * <em><font class="skcolor_ljg">哈尔滨</font>（Harbin） <font class="skcolor_ljg">小麦王</font>啤酒330ml*4*6听  整箱装</em>
             * //item.jd.com/2600210.html
             * <a target="_blank" title="哈尔滨（Harbin） 小麦王啤酒330ml*4*6听  整箱装" href="//item.jd.com/1154022.html" onclick="searchlog(1,1154022,1,1,'','flagsClk=648')">
							<em><font class="skcolor_ljg">哈尔滨</font>（Harbin） <font class="skcolor_ljg">小麦王</font>啤酒330ml*4*6听  整箱装</em>
             */
            #endregion 说明

            string url = string.Format("http://search.jd.com/Search?keyword={0}&enc=utf-8&pvid=4seb1kri.fhkknd", keyword);
            string rtn = GetURLResult(url);
            if (!string.IsNullOrEmpty(rtn))
            {
                string pageNum = Regex.Match(rtn, @"<i>\d{1,3}</i>").Value;
                string sPageNum = Regex.Match(rtn, "page_count:\"12\"").Value;
                if (!string.IsNullOrEmpty(pageNum))
                {

                    //获取商品数量及页数
                    string wareNum = Regex.Match(rtn, "<div class=\"f-result-sum\">共<span id=\"J_resCount\" class=\"num\">\\d{1,4}</span>件商品</div>").Value;
                    //商品数量
                    int wNum = 0;
                    if (!string.IsNullOrEmpty(wareNum))
                    {
                        wNum = int.Parse(Regex.Match(wareNum, "\\d{1,4}").Value);
                    }
                    //总页数
                    int iPageNum = int.Parse(pageNum.Replace("<i>", "").Replace("</i>", ""));
                    pageNum = Regex.Match(sPageNum, "\\d{1,4}").Value;
                    int.TryParse(pageNum, out iPageNum);
                    //int iPageNum = 0;
                    //int.TryParse(iPageNum, out iPageNum);

                    ParseResult(rtn);
                    int iCount = 1;
                    const int multiplier = 60;
                    int iNowPage = 3;
                    for (int i = 2; i < iPageNum; i++)
                    {
                        //keyword=蒙牛牛奶
                        //ev=exbrand_蒙牛@
                        //http://search.jd.com/Search?keyword=%E8%92%99%E7%89%9B%E7%89%9B%E5%A5%B6&enc=utf-8&qrst=1&rt=1&stop=1&vt=2&bs=1&ev=exbrand_%E8%92%99%E7%89%9B%40&page=3&s=61&click=0
                        //http://search.jd.com/Search?keyword={0}&enc=utf-8&qrst=1&rt=1&stop=1&vt=2&bs=1&ev=exbrand_%E8%92%99%E7%89%9B%40&page={1}&s={2}&click=0
                        //http://search.jd.com/Search?keyword={0}&enc=utf-8&wq={0}&pvid=o7m60kri.fhkknd#keyword={0}&enc=utf-8&qrst=1&rt=1&stop=1&vt=2&offset=1&page={1}&s={2}&click=0
                        url = string.Format("http://search.jd.com/Search?keyword={0}&enc=utf-8&qrst=1&rt=1&stop=1&vt=2&bs=1&page={1}&s={2}&click=0",
                                keyword, iNowPage, iCount * multiplier);
                        rtn = GetURLResult(url);
                        ParseResult(rtn);
                        iNowPage += 2;
                        iCount++;
                    }

                }
            }

            return _sites;
        }
    }
}
